import axios from 'axios'
import storage from 'store'
import { ACCESS_TOKEN } from './types'
import qs from 'qs'
import { Dialog , Notify } from 'vant';
import stroe from '../store';
import router from '../router';

// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 6000 // 请求超时时间
})

let needLoadingRequestCount = 0
let timer = null
function showFullScreenLoading() {
    // console.log(timer,'starttimer')
    if (needLoadingRequestCount === 0 && !timer) {
        timer = setTimeout(()=>{
            stroe.dispatch('setLoading',true)
        },500)
    }
    needLoadingRequestCount++
}

 function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
        needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        if(timer){
            clearTimeout(timer)
            timer = null
            stroe.dispatch('setLoading',false)
        }
    }
}

// 异常拦截处理器
const errorHandler = (error) => {
    tryHideFullScreenLoading()
    if (error.response) {
        const data = error.response
        // 从 localstorage 获取 token
        const token = storage.get(ACCESS_TOKEN)
        if (error.response.status === 403) {
        // notification.error({
        //     message: 'Forbidden',
        //     description: data.message
        // })
            Notify({ type: 'danger', message: data.errMessage });
        }
        if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
            Notify({ type: 'danger', message: data.errMessage });
        }
    }
    return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
    showFullScreenLoading()
    const token = storage.get(ACCESS_TOKEN)
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (token) {
        console.log(token,'token');
        config.headers[ACCESS_TOKEN] = token
    }
    // if(!config.headers.file){
    //     for ( var key in config.data ){
    //         if ( (!config.data[key] || config.data[key] === '') && config.data[key] !== 0){
    //             delete config.data[key]
    //         }
    //     }
    //     // console.log('是否会走这里')
    //     if (token && config.url != '/usercenter/app/login/client') {
    //     // config.headers['access-token'] = token
    //     // console.log(config,'config')
    //         var tokenObj = new Object()
    //         tokenObj[ACCESS_TOKEN] = token
    //         config.data = Object.assign(config.data,tokenObj)
    //     }
    //     config.data = qs.stringify(config.data)
    // }else{
    //     config.data.append(ACCESS_TOKEN,token)
    // }
    // console.log(config,'config')
    return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
    tryHideFullScreenLoading()
    console.log(response,'response')
    if(response.data.errCode == 'ERROR_TOKEN'){
        // token 过期的操作
        Dialog.confirm({
            title: '登录过期',
            message: '您的登录已经过期，请重新登录',
        })
        .then(() => {
            // on confirm
            storage.clearAll()
            // window.location.reload()
            router.push({name:'login'})
        })
        .catch(() => {
            // on cancel
        });
    }else if(response.url != '/accountcenter/app/request/ali/top/up'){
        return response.data
    }else{
        return response
    }
}, errorHandler)

export default request